package kr.or.kead.daegu.global.OutputUI;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.swing.table.AbstractTableModel;

import kr.hkit.framework.dao.CloseDaoUtil;
import kr.hkit.framework.dao.LoadPropertyDAO;
import kr.or.kead.daegu.global.Config;
import kr.or.kead.daegu.global.DTO.Business;
import kr.or.kead.daegu.global.DTO.Emp;
import kr.or.kead.daegu.global.DTO.Product;
import kr.or.kead.daegu.global.Service.DbDao;

public class CustomTableModel extends AbstractTableModel {
	Connection con;
	String sql;
	String[] tableColumnNames;
	Class[] tableColumnClasses;
	ArrayList lists;
	int flag;
	
	Emp emp;
	Product product;
	Business business;
	
	public CustomTableModel(int i, String sql) {
		this.con = LoadPropertyDAO.getConnection();
		this.sql = sql;
		this.flag = i;
		tableColumnNames = Config.LBL_LIST_COLNAME[flag];
		tableColumnClasses = Config.LBL_LIST_COLCLASS[flag];
		getData();
	}
	
	public void getData(){
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		lists = new ArrayList<>();
		try {
			pstmt = con.prepareStatement(sql);
			rs = pstmt.executeQuery();
			while(rs.next()){
				switch(flag){
				case 0:
					lists.add(new Emp(rs.getString(1), rs.getString(2), rs.getString(3))); break;
				case 1:
					lists.add(new Product(rs.getString(1), rs.getString(2), rs.getInt(3), rs.getInt(4)));break;
				case 2:
					lists.add(new Business(rs.getString(1), rs.getString(2), rs.getString(3))); break;
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			CloseDaoUtil.close(rs, pstmt);
		}
	}
	
	@Override
	public Class<?> getColumnClass(int columnIndex) {
		return tableColumnClasses[columnIndex];
	}

	@Override
	public String getColumnName(int column) {
		return tableColumnNames[column];
	}	
	@Override
	public int getColumnCount() {
		return tableColumnNames.length;
	}

	@Override
	public int getRowCount() {
		return lists.size();
	}

	@Override
	public Object getValueAt(int row, int col) {
		switch(flag){
		case 0:
			if (col==0) emp = (Emp) lists.get(row);
			switch(col){
			case 0:return emp.getCode();
			case 1:return emp.getName();
			case 2:return emp.getGrade();
			}
			break;
		case 1:
			if (col==0) product = (Product) lists.get(row);
			switch(col){
			case 0:return product.getpCode();
			case 1:return product.getpName();
			case 2:return product.getRegprice();
			case 3:return product.getPrimeprice();
			}
			break;
		case 2:
			if (col==0) business = (Business) lists.get(row);
			switch(col){
			case 0:return business.getbCode();
			case 1:return business.getbName();
			case 2:return business.getbGrade();
			}
			break;
		}
		return null;
	}

}
